package com.fanjia.crm.config;

import com.fanjia.crm.model.Permission;
import com.fanjia.crm.service.IPermissionService;
import com.fanjia.crm.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.thymeleaf.util.StringUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * Created by FanJia on 2020/9/20 11:33
 */
@Configuration
public class MyUserDetailConfig implements UserDetailsService {

    @Autowired
    public PasswordEncoder passwordEncoder;

    @Autowired
    IUserService userService;
    @Autowired
    IPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println(username);

        com.fanjia.crm.model.User dbUser = userService.findByUsername(username);
        System.out.println(dbUser);
        if(dbUser==null){
            return null;
        }

        String pwd = passwordEncoder.encode(dbUser.getPassword());
        return new User(username
                , pwd
                , getCurrentUserAuthorities(dbUser.getId())
        );
    }

    public Collection<? extends GrantedAuthority> getCurrentUserAuthorities(Integer userId){
        List<GrantedAuthority> list = new ArrayList<>();
//        list.add(new SimpleGrantedAuthority("COURSEORDER_READ"));
//        list.add(new SimpleGrantedAuthority("COURSEORDER_DELETE"));
        //查当前用户的权限
        List<Permission> pmsList = permissionService.findPermissionListByUserId(userId);
        for(Permission p : pmsList){
            if(!StringUtils.isEmpty(p.getAuthorization_flag())){
                list.add(new SimpleGrantedAuthority(p.getAuthorization_flag()));
            }
        }


        return list;
    }



}
